package cn.tedu.charging.device.config;

import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * Canal配置类
 */
@Slf4j
@Configuration
public class CanalConfig {

    @Value("${canal.server.host:127.0.0.1:11111}")
    private String canalServerHost;

    @Value("${canal.server.destination:charging}")
    private String destination;

    @Value("${canal.server.username:}")
    private String username;

    @Value("${canal.server.password:}")
    private String password;

    /**
     * 创建Canal连接器Bean
     * @return CanalConnector
     */
    @Bean
    public CanalConnector canalConnector() {
        log.info("初始化Canal连接器 host:{} destination:{} username:{}", canalServerHost, destination, username);
        
        try {
            // 解析host和port
            String[] hostPort = canalServerHost.split(":");
            String host = hostPort[0];
            int port = Integer.parseInt(hostPort[1]);
            
            SocketAddress address = new InetSocketAddress(host, port);
            
            // 创建单连接器
            CanalConnector connector;
            if (username != null && !username.isEmpty()) {
                connector = CanalConnectors.newSingleConnector(
                        address, 
                        destination, 
                        username, 
                        password);
            } else {
                connector = CanalConnectors.newSingleConnector(
                        address, 
                        destination, 
                        "", 
                        "");
            }
            
            log.info("Canal连接器初始化完成");
            return connector;
        } catch (Exception e) {
            log.error("Canal连接器初始化失败: {}", e.getMessage(), e);
            throw new RuntimeException("Canal连接器初始化失败", e);
        }
    }
}